﻿using InfonavaEye.common;
using InfonavaEye.components;
using InfonavaEye.model;
using InfonavaEye.model.wjapi;
using InfonavaEye.Service;
using Sylan.Common.Util;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;

namespace InfonavaEye.handler
{

    public enum OCRModelEnum
    {
        LOCALSTRAIGHT = 1,
        SERVER = 2,

    }
    public class OCRAndStraightService
    {
        public static List<StraightImg> straightImgList = new List<StraightImg>();
        private static ConcurrentQueue<OCRResult> fileUploadQueue = new ConcurrentQueue<OCRResult>();

        public static Dictionary<string, int> ocrResultCount = new Dictionary<string, int>();
        
        public delegate void OCRServerDoneDelegate(OCRResult result);
        public static event OCRServerDoneDelegate ocrServerDoneDelegate;


        public delegate void CaptrueDoneDelegate();
        public static event CaptrueDoneDelegate captrueDoneDelegate;

        private static OCRAndStraightService instance;

        private bool scanEnd = false;

        public static int ocrTotalCount = 0;
        public static OCRAndStraightService Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new OCRAndStraightService();
                }
                return instance;
            }
        }
        public OCRAndStraightService() { }


        public void uploadStraightOdlImg(OCRResult result, string captureOptSN,int captureNailQueueCount)
        {
            result.captureOptSN= captureOptSN;
            if (captureNailQueueCount<=0) {
                result.isLastCount= true;
            }
            fileUploadQueue.Enqueue(result);
            if (!uploadThreadRun) {
                uploadThreadRun = true;
                ThreadHelper.ExcuteThreadTask(() =>
                {
                    upLoadFile();
                });
            }
        }
        bool uploadThreadRun = false;
        public void upLoadFile() {
               scanEnd = false;
                uploadThreadRun =fileUploadQueue.TryDequeue(out var result);
              //  Console.WriteLine("upLoadFile uploadThreadRun:{0}   fileUploadQueue:{1}", uploadThreadRun, fileUploadQueue.Count);
                if (!uploadThreadRun) {
                    scanEnd = true;
                    return;
                }
                //上传图片
                var nail = result.nail;
                UploadFileParams file = new UploadFileParams();
                file.shape = result.shape;
                file.filePath = result.filePath;
                file.ScanSN = result.captureOptSN;
                file.DeviceNo = Eps.Ai.Common.Config.UPPER_DEVICE_NO;
                file.BoxTemplateCode = "";                              //TODO ???
                file.Segment = nail.area.code;
                file.rowNumber = nail.point.Y.ToString();
                file.columnNumber = nail.point.X.ToString();
                file.fileName = result.captureOptSN + "_" + Path.GetFileName(result.filePath);
                scanEnd = scanEnd ? scanEnd : result.isLastCount;
                file.isLast = scanEnd;
                UploadFileResponse uplocadResp = WuJingStroageService.Instance.UploadFile(file);
             
                if (!uplocadResp.Success)
                {
                    upLoadFile();
                return;
                }
                //ImageShapeEnum.CIRCLE  拉直+OCR  其他的直接OCR
                StraightImg si = new StraightImg()
                {
                    captureOptSN = result.captureOptSN,
                    nail = result.nail,
                    status = result.status,
                    rowNum = result.rowNum,
                    shape = result.shape,
                    filePath = result.filePath,
                    isSample = result.isSample,
                    code = result.code,
                    errorMsg = result.errorMsg,
                    codeOld = result.codeOld,
                    straightFilePath = result.straightFilePath,
                    straightFilePathOld = result.straightFilePathOld,
                    FileMD5 = uplocadResp.FileMD5,
                    RequestId = uplocadResp.RequestId,
                    ServerType = uplocadResp.ServerType,
                    ContentLength = uplocadResp.ContentLength,
                    FileUrl = uplocadResp.FileUrl,
                    FileId = uplocadResp.FileId,
                };
               // Console.WriteLine("uplocadResp=============>{0},{1}", uplocadResp.Success, result.filePath);
                straightImgList.Add(si);
                if (captrueDoneDelegate!=null&& fileUploadQueue.Count<=0) {
                    captrueDoneDelegate.Invoke();
                }
                if (scanEnd) {
                 queryOCRResult(result.captureOptSN);
                }
                upLoadFile();
        }

        public void sendStraightReq(string captureOptSN) {
            ocrTotalCount = FormDataBridge.OCRDataDic.Count;
            this.scanEnd = true;
            /*  if (straightImgList.Count <= 0)
              {
                  return;
              }

              if (uploadThreadRun)
              {
                  return;
              }
            //  queryOCRResult(captureOptSN);

              ThreadHelper.ExcuteThreadTask(() =>
              {
                  ThreadHelper.Sleep(2000);
                  if (uploadThreadRun)
                  {
                      queryOCRResult(captureOptSN);
                      return;
                  }
                  List<StraightenImg> ImgList = new List<StraightenImg>();
                  foreach (StraightImg si in straightImgList)
                  {
                      var nail = si.nail;
                      StraightenImg img = new StraightenImg()
                      {
                          ImgURl = si.FileUrl,
                          Segment = nail.area.code,
                          rowNumber = nail.point.Y.ToString(),
                          columnNumber = nail.point.X.ToString(),
                          FileId= si.FileId
                      };
                      ImgList.Add(img);
                  }
                  StraightenReqParams srParams = new StraightenReqParams()
                  {
                      ScanSN = captureOptSN,
                      BoxTemplateCode = "",
                      ImgList = ImgList
                  };
                  var service = ReportServiceFactory.getService();
                  Boolean result = service.sendStraightReq(srParams);
                  if (result)
                  {
                      queryOCRResult(captureOptSN);
                  }
              });*/
        }

        bool queryResult = false;
        public void queryOCRResult(string captureOptSN) {
            //开启异步线程查询拉直和OCR的结果
            ThreadHelper.ExcuteThreadTask(() =>
            {
                if (queryResult) {
                    return;
                }
                queryResult= true;
                //每秒查询一次
                ThreadHelper.Sleep(1000);
                var service = ReportServiceFactory.getService();
                List<OCRServerResult> ocrResultList = service.queryOCRResult(captureOptSN);
                if (ocrResultList==null|| ocrResultList.Count<=0)
                {
                    queryResult = false;
                    queryOCRResult(captureOptSN);
                    return;
                }
                Dictionary<string, OCRServerResult> ocrResultDict = new Dictionary<string, OCRServerResult>();

                int oCount = 0;
                foreach (OCRServerResult osr in ocrResultList)
                {
                    ocrResultDict.Add(osr.imageId, osr);
                    oCount = oCount + 1;
                }
                if (ocrResultCount.ContainsKey(captureOptSN))
                {
                    oCount = ocrResultCount[captureOptSN] + oCount;
                    ocrResultCount[captureOptSN] = oCount;
                }
                else {
                    ocrResultCount.Add(captureOptSN, oCount);
                }
               
                for (int i= straightImgList.Count-1;i>=0;i--) {
                    StraightImg si = straightImgList[i];
                    OCRResult oCRResult = new OCRResult()
                    {
                        nail = si.nail,
                        rowNum = si.rowNum,
                        shape = si.shape,
                        code = "未识别",
                        errorMsg = si.errorMsg,
                        codeOld = si.codeOld,
                        filePath = si.filePath,
                        straightFilePath = si.straightFilePath,
                        straightFilePathOld = si.straightFilePathOld,
                        status = si.status,
                        isSample = si.isSample,
                    };
                    if (ocrResultDict.ContainsKey(si.FileId))
                    {
                        OCRServerResult osr = ocrResultDict[si.FileId];
                        oCRResult.code = osr.ocrText;
                        oCRResult.straightFilePath = osr.straightImgUrl;
                    }
                    if (ocrServerDoneDelegate != null)
                    {
                        ocrServerDoneDelegate.Invoke(oCRResult);
                        straightImgList.Remove(si);
                    }
                }
                queryResult = false;
                // Console.WriteLine("ocrTotalCount=={0},ocrResultCount: {1}", ocrTotalCount, ocrResultCount[captureOptSN]);
                if (ocrResultCount[captureOptSN] >= ocrTotalCount)
                {
                    service.cleanOCRResult(captureOptSN);
                    ocrResultCount.Remove(captureOptSN);
                }
                else
                {
                    queryOCRResult(captureOptSN);
                }
            });
        }

    }
}
